package com.testapp.supers.app;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.testapp.supers.app.bean.CompositeIndexBean;
import com.testapp.supers.app.bean.IncomeBean;
import com.testapp.supers.app.bean.LineChartBean;
import com.testapp.supers.app.bean.RecordWeekBean;
import com.testapp.supers.app.bean.RecordWeekDataBean;
import com.testapp.supers.app.utils.DateUtil;
import com.testapp.supers.app.utils.LocalJsonAnalyzeUtil;
import com.testapp.supers.app.view.LineChartMarkView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class SearchresultActivity extends AppCompatActivity {

    BarChart barChart;//柱状图
    BarChart barChart2;//柱状图
    BarChart barChart3;//柱状图
    BarChart barChart4;//柱状图
    private LineChart lineChart;
    private XAxis xAxis;                //X轴
    private YAxis leftYAxis;            //左侧Y轴
    private YAxis rightYaxis;           //右侧Y轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
//  private MyMarkerView markerView;    //标记视图 即点击xy轴交点时弹出展示信息的View 需自定义

    private LineChartBean lineChartBean;
    private List<IncomeBean> incomeBeanList;//山体倾斜率
    private List<CompositeIndexBean> shanghai;//土壤含水率
    private List<CompositeIndexBean> shenzheng;//环境雨量
    private List<CompositeIndexBean> GEM;//土壤松弛度

    private ConstraintLayout cl_shanghai;
    private View view_shanghai;
    private ConstraintLayout cl_shenzhen;
    private View view_shenzhen;
    private ConstraintLayout cl_gem;
    private View view_gem;
    private Button button1;
    private MediaPlayer mp;
    private Vibrator vibrator;
    private SweetAlertDialog sweetAlertDialog;
    private RecordWeekBean recordWeekBean;
    //柱状图数据
    List<BarEntry> yVals = new ArrayList<>();
    String[] xValues = new String[9];//只有7条数据为什么定义长度为9的数组？没关系不影响？
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final boolean b = supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_searchresult);
        initView();
        initData();//主要解析本地json获取假数据
        lineChart = findViewById(R.id.lineChart);
        barChart = findViewById(R.id.chart1);
        barChart2 = findViewById(R.id.chart2);
        barChart3 = findViewById(R.id.chart3);
        barChart4 = findViewById(R.id.chart4);
        //初始化图表
        initChart(lineChart);
        //显示图表
        showLineChart(incomeBeanList, "山体倾斜率", Color.CYAN);
        //添加另一条曲线
        addLine(shanghai, "土壤含水率", getResources().getColor(R.color.orange));
        //设置点击图表后显示的view
        setMarkerView();
        initAndShowBarChart();
        showBarChartAlong2(yVals, xValues, "", Color.parseColor("#EE6363"));
        showBarChartAlong3(yVals, xValues, "", Color.parseColor("#9400D3"));
        showBarChartAlong4(yVals, xValues, "", Color.parseColor("#FF3E96"));
    }

    private void initView() {

        cl_shanghai = findViewById(R.id.cl_shanghai);
        view_shanghai = findViewById(R.id.view_shanghai);
        cl_shanghai.setOnClickListener(listener);

        cl_shenzhen = findViewById(R.id.cl_shenzhen);
        view_shenzhen = findViewById(R.id.view_shenzhen);
        cl_shenzhen.setOnClickListener(listener);

        cl_gem = findViewById(R.id.cl_gem);
        view_gem = findViewById(R.id.view_gem);
        cl_gem.setOnClickListener(listener);

        button1 = findViewById(R.id.button1);
        button1.setOnClickListener(listener);
    }
    private void initData() {
        //准备警报声音并监听，实现循环播放
        mp = MediaPlayer.create(this, R.raw.music);
        //准备振动
        vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mp == null) {return;}
                mp.start();
                mp.setLooping(true);
            }
        });

        //获取数据
        lineChartBean = LocalJsonAnalyzeUtil.JsonToObject(this, "line_chart.json", LineChartBean.class);
        incomeBeanList = lineChartBean.getGRID0().getResult().getClientAccumulativeRate();

        shanghai = lineChartBean.getGRID0().getResult().getCompositeIndexShanghai();
        shenzheng = lineChartBean.getGRID0().getResult().getCompositeIndexShenzhen();
        GEM = lineChartBean.getGRID0().getResult().getCompositeIndexGEM();
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.cl_shanghai:
                    view_shanghai.setBackground(getResources().getDrawable(R.drawable.shape_round_orange));

                    view_gem.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));
                    view_shenzhen.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));

                    resetLine(1, shanghai, "土壤含水率", getResources().getColor(R.color.orange));
                    break;
                case R.id.cl_shenzhen:
                    view_shenzhen.setBackground(getResources().getDrawable(R.drawable.shape_round_orange));

                    view_gem.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));
                    view_shanghai.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));

                    resetLine(1, shenzheng, "环境雨量", getResources().getColor(R.color.orange));
                    break;
                case R.id.cl_gem:
                    view_gem.setBackground(getResources().getDrawable(R.drawable.shape_round_orange));
                    view_shanghai.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));
                    view_shenzhen.setBackground(getResources().getDrawable(R.drawable.shape_round_gray));

                    resetLine(1, GEM, "土壤松弛率", getResources().getColor(R.color.orange));
                    break;

                case R.id.button1:
                    mp.start();
//                    vibrator.vibrate(10000);
                    long[] pattern = {0,1000,0,1000,0,1000,0,1000,0,1000,0,1000,0,1000};
                    vibrator.vibrate(pattern,0);
                    sweetAlertDialog = new SweetAlertDialog(SearchresultActivity.this);
                    sweetAlertDialog.setTitleText("收到警报请返回主页查看")
                            .setConfirmText("OK")
                            .show();
                    break;
            }
        }
    };

    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart) {
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(true);
        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);

        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        leftYAxis = lineChart.getAxisLeft();
        rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(6, true);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        legend.setEnabled(false);
        Description description = new Description();
        description.setText("山体状况实时监控表");
        description.setEnabled(true);
        lineChart.setDescription(description);
    }


    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
        lineDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                DecimalFormat df = new DecimalFormat(".00");
                return df.format(value * 100) + "%";
            }
        });
    }

    /**
     * 展示曲线
     *
     * @param dataList 数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     */
    public void showLineChart(final List<IncomeBean> dataList, String name, int color) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            IncomeBean data = dataList.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, (float) data.getValue());
            entries.add(entry);
        }
        //X轴值的定义
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String tradeDate = dataList.get((int) value % dataList.size()).getTradeDate();
                return DateUtil.formatDateToMD(tradeDate);
            }
        });
        //设置X轴分割数量
        xAxis.setLabelCount(6, false);
        //Y轴定义
        leftYAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ((int) (value * 100)) + "%";
            }
        });
        leftYAxis.setLabelCount(8);
        rightYaxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ((int) (value * 100)) + "%";
            }
        });
        rightYaxis.setLabelCount(8);
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
    }

    /**
     * 设置线条填充背景颜色
     *
     * @param drawable
     */
    public void setChartFillDrawable(Drawable drawable) {
        if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {
            LineDataSet lineDataSet = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
            //避免在 initLineDataSet()方法中 设置了 lineDataSet.setDrawFilled(false); 而无法实现效果
            lineDataSet.setDrawFilled(true);
            lineDataSet.setFillDrawable(drawable);
            lineChart.invalidate();
        }
    }

    /**
     * 设置 可以显示X Y 轴自定义值的 MarkerView
     */
    public void setMarkerView() {
        LineChartMarkView mv = new LineChartMarkView(this, xAxis.getValueFormatter());
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
        lineChart.invalidate();
    }

    /**
     * 添加曲线
     */
    private void addLine(List<CompositeIndexBean> dataList, String name, int color) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            CompositeIndexBean data = dataList.get(i);
            Entry entry = new Entry(i, (float) data.getRate());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        lineChart.getLineData().addDataSet(lineDataSet);
        lineChart.invalidate();
    }

    //重置某条曲线
    public void resetLine(int position, List<CompositeIndexBean> dataList, String name, int color) {
        LineData lineData = lineChart.getData();
        List<ILineDataSet> list = lineData.getDataSets();
        if (list.size() <= position) {
            return;
        }

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            CompositeIndexBean data = dataList.get(i);
            Entry entry = new Entry(i, (float) data.getRate());
            entries.add(entry);
        }

        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);

        lineData.getDataSets().set(position, lineDataSet);
        lineChart.invalidate();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mp.stop();
        mp=null;
        vibrator.cancel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //显示柱状图
    public void showBarChartAlong(List<BarEntry> yVals, String[] xValues, String label, int color) {
        //智障了，之前一直想怎么自己去计算最大最小值，做了很多白活，但其实如果我们什么都不去设置框架会自动帮我们设置好
        BarChartManager barChartManager = new BarChartManager(barChart,1f);
        barChartManager.showBarChart(yVals, xValues,label, color);
    }
    public void initAndShowBarChart(){
        //获取数据
        recordWeekBean = LocalJsonAnalyzeUtil.JsonToObject(this, "bar1.json", RecordWeekBean.class);
        int n = 0;
        for(RecordWeekDataBean m : recordWeekBean.getRows()) {
            System.out.println("key:" + m.getDate() + " value:" + m.getCount());
            int firstIndex = m.getDate().indexOf('-'); //找到第一个-所在位置
            String time = m.getDate().substring(firstIndex + 1, m.getDate().length());//截取出月-日
            xValues[n++] = time;
            yVals.add(new BarEntry((float) n, m.getCount()));
        }
        barChart.animateXY(1000,1000);
        showBarChartAlong(yVals, xValues, "", Color.parseColor("#000000"));
    }

    //显示柱状图
    public void showBarChartAlong2(List<BarEntry> yVals, String[] xValues, String label, int color) {
        //智障了，之前一直想怎么自己去计算最大最小值，做了很多白活，但其实如果我们什么都不去设置框架会自动帮我们设置好
        BarChartManager barChartManager2 = new BarChartManager(barChart2,1f);
        barChartManager2.showBarChart(yVals, xValues,label, color);
    }
    public void initAndShowBarChart2(){
        //获取数据
        recordWeekBean = LocalJsonAnalyzeUtil.JsonToObject(this, "bar1.json", RecordWeekBean.class);
        int n = 0;
        for(RecordWeekDataBean m : recordWeekBean.getRows()) {
            System.out.println("key:" + m.getDate() + " value:" + m.getCount());
            int firstIndex = m.getDate().indexOf('-'); //找到第一个-所在位置
            String time = m.getDate().substring(firstIndex + 1, m.getDate().length());//截取出月-日
            xValues[n++] = time;
            yVals.add(new BarEntry((float) n, m.getCount()));
        }
        barChart2.animateXY(1000,1000);
        showBarChartAlong2(yVals, xValues, "", Color.parseColor("#000000"));
    }

    //显示柱状图
    public void showBarChartAlong3(List<BarEntry> yVals, String[] xValues, String label, int color) {
        //智障了，之前一直想怎么自己去计算最大最小值，做了很多白活，但其实如果我们什么都不去设置框架会自动帮我们设置好
        BarChartManager barChartManager = new BarChartManager(barChart3,1f);
        barChartManager.showBarChart(yVals, xValues,label, color);
    }
    public void initAndShowBarChart3(){
        //获取数据
        recordWeekBean = LocalJsonAnalyzeUtil.JsonToObject(this, "bar1.json", RecordWeekBean.class);
        int n = 0;
        for(RecordWeekDataBean m : recordWeekBean.getRows()) {
            System.out.println("key:" + m.getDate() + " value:" + m.getCount());
            int firstIndex = m.getDate().indexOf('-'); //找到第一个-所在位置
            String time = m.getDate().substring(firstIndex + 1, m.getDate().length());//截取出月-日
            xValues[n++] = time;
            yVals.add(new BarEntry((float) n, m.getCount()));
        }
        barChart3.animateXY(1000,1000);
        showBarChartAlong3(yVals, xValues, "", Color.parseColor("#000000"));
    }

    //显示柱状图
    public void showBarChartAlong4(List<BarEntry> yVals, String[] xValues, String label, int color) {
        //智障了，之前一直想怎么自己去计算最大最小值，做了很多白活，但其实如果我们什么都不去设置框架会自动帮我们设置好
        BarChartManager barChartManager = new BarChartManager(barChart4,1f);
        barChartManager.showBarChart(yVals, xValues,label, color);
    }
    public void initAndShowBarChart4(){
        //获取数据
        recordWeekBean = LocalJsonAnalyzeUtil.JsonToObject(this, "bar1.json", RecordWeekBean.class);
        int n = 0;
        for(RecordWeekDataBean m : recordWeekBean.getRows()) {
            System.out.println("key:" + m.getDate() + " value:" + m.getCount());
            int firstIndex = m.getDate().indexOf('-'); //找到第一个-所在位置
            String time = m.getDate().substring(firstIndex + 1, m.getDate().length());//截取出月-日
            xValues[n++] = time;
            yVals.add(new BarEntry((float) n, m.getCount()));
        }
        barChart4.animateXY(1000,1000);
        showBarChartAlong4(yVals, xValues, "", Color.parseColor("#000000"));
    }
}
